package com.ymttest.business.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;

import com.ymatou.auth.parameter.DeviceAuthStatusRequestDtoBean;
import com.ymatou.auth.parameter.GetDualSecurityResultRequestDtoBean;
import com.ymatou.auth.parameter.IpAreaAuthManageRequestDtoBean;
import com.ymatou.auth.parameter.IpAreaAuthStatusRequestDtoBean;
import com.ymatou.auth.parameter.LoginAuthBean;
import com.ymatou.auth.parameter.PasswordRequestDtoBean;
import com.ymatou.auth.parameter.RemoveTokenBean;
import com.ymatou.auth.parameter.SecurityQuestionAnswer;
import com.ymatou.auth.parameter.SetDualSecurityRequestDtoBean;
import com.ymatou.auth.parameter.SetSecurityQuestionBean;
import com.ymatou.auth.parameter.SignAuthBean;
import com.ymatou.auth.service.DeviceAuthStatusRequestDtoCall;
import com.ymatou.auth.service.GetDualSecurityResultRequestDtoCall;
import com.ymatou.auth.service.IpAreaAuthManageRequestDtoCall;
import com.ymatou.auth.service.IpAreaAuthStatusRequestDtoCall;
import com.ymatou.auth.service.LoginAuthCall;
import com.ymatou.auth.service.PasswordRequestDtoCall;
import com.ymatou.auth.service.RemoveTokenCall;
import com.ymatou.auth.service.SetDualSecurityRequestDtoCall;
import com.ymatou.auth.service.SetSecurityQuestionCall;
import com.ymatou.auth.service.SignAuthCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.data.LoginSafeConfiguration;
import com.ymttest.utils.TestDataManager;

/************************************************************************************
 * @File name :AuthCallService.java
 * @Author : zhouyi
 * @Date : 2015年10月17日
 * @Copyright : 洋码头
 ************************************************************************************/
public class AuthCallService {
	static Map<String, Map> loginCache = new HashMap<String, Map>();

	/**
	 * 登入 获取AccessToken
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> authLogin(String UserName, String pas) {
		HashMap m = new HashMap();
		try {
			//添加loginCache缓存，由于目前auth添加了风控频繁登入会失败，所以登入后保存在静态Map中，使用前signAuth保证可用
			if (loginCache.containsKey(UserName)) {
				Map mtemp = loginCache.get(UserName);
				String tuid = String.valueOf(signAuth(mtemp.get("accessToken").toString()).get("userId"));
				if (tuid.equals(mtemp.get("userId").toString())) {
					return mtemp;
				}
			}
			LoginAuthBean lab = new LoginAuthBean();
			LoginAuthCall lac = new LoginAuthCall();
			lab.setLoginId(UserName);
			lab.setPas(pas);
			lab.setSourceType("MainSite");
			//lab.setClientIp(TestDataManager.getRandomIp());
			lab.setClientIp("127.16.14.35");
			lac.setData(false, lab);
			Logger.comment("用户:" + UserName + "登录");
			lac.callService();
			m.put("userId", lac.getUserData().getUserId());
			m.put("userName", lac.getUserData().getLoginId());
			m.put("accessToken", lac.getUserData().getSign());
			m.put("loginMobile", lac.getUserData().getLoginMobile());
			loginCache.put(UserName, m);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}
	public static Map<String, Object> authLogin(String UserName, String pas,String sourceType,String ip) {
		HashMap m = new HashMap();
		try {
			//添加loginCache缓存，由于目前auth添加了风控频繁登入会失败，所以登入后保存在静态Map中，使用前signAuth保证可用
			if (loginCache.containsKey(UserName)) {
				Map mtemp = loginCache.get(UserName);
				String tuid = String.valueOf(signAuth(mtemp.get("accessToken").toString()).get("userId"));
				if (tuid.equals(mtemp.get("userId").toString())) {
					return mtemp;
				}
			}
			LoginAuthBean lab = new LoginAuthBean();
			LoginAuthCall lac = new LoginAuthCall();
			lab.setLoginId(UserName);
			lab.setPas(pas);
			lab.setSourceType(sourceType);
			lab.setClientIp(ip);
			lac.setData(false, lab);
			Logger.comment("用户:" + UserName + "登录");
			lac.callService();
			m.put("userId", lac.getUserData().getUserId());
			m.put("userName", lac.getUserData().getLoginId());
			m.put("accessToken", lac.getUserData().getSign());
			m.put("loginMobile", lac.getUserData().getLoginMobile());
			if(lac.getString("Success").equals("true")){
				loginCache.put(UserName, m);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}
	public static Map<String, Object> authLogin(String UserName, String pas,String sourceType,String ip,String tokenSource) {
		HashMap m = new HashMap();
		try {
			//添加loginCache缓存，由于目前auth添加了风控频繁登入会失败，所以登入后保存在静态Map中，使用前signAuth保证可用
			if (loginCache.containsKey(UserName)) {
				Map mtemp = loginCache.get(UserName);
				String tuid = String.valueOf(signAuth(mtemp.get("accessToken").toString()).get("userId"));
				if (tuid.equals(mtemp.get("userId").toString())) {
					return mtemp;
				}
			}
			LoginAuthBean lab = new LoginAuthBean();
			LoginAuthCall lac = new LoginAuthCall();
			lab.setLoginId(UserName);
			lab.setPas(pas);
			lab.setSourceType(sourceType);
			lab.setClientIp(ip);
			lab.setTokenSource(tokenSource);
			lac.setData(false, lab);
			Logger.comment("用户:" + UserName + "登录");
			lac.callService();
			m.put("userId", lac.getUserData().getUserId());
			m.put("userName", lac.getUserData().getLoginId());
			m.put("accessToken", lac.getUserData().getSign());
			m.put("loginMobile", lac.getUserData().getLoginMobile());
			if(lac.getString("Success").equals("true")){
				loginCache.put(UserName, m);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}
	
	
	public static LoginAuthCall login(String UserName, String pas,String sourceType,String ip) {

		LoginAuthBean lab = new LoginAuthBean();
		LoginAuthCall lac = new LoginAuthCall();
		
		try {

			lab.setLoginId(UserName);
			lab.setPas(pas);
			lab.setSourceType(sourceType);
			lab.setClientIp(ip);
			lac.setData(false, lab);
			Logger.comment("用户:" + UserName + "登录");
			lac.callService();

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lac;
	}
	
	/**
	 * Token认证
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> signAuth(String AccessToken,String ip) {
		HashMap m = new HashMap();
		try {
			SignAuthBean sab = new SignAuthBean();
			SignAuthCall sac = new SignAuthCall();
			sab.setToken(AccessToken);
			sab.setSClientType("MainSite");
			sab.setClientIp(ip);
			sac.setData(false, sab);
			Logger.comment("用户token登录认证");
			sac.callService();
			Logger.debug("Token认证 call:" + sac.getEntityString());
			Logger.debug("Token认证 response:" + sac.getReturnData());
			m.put("success", sac.getSuccess());
			if (sac.getSuccess()) {
				m.put("userId", sac.getUserId());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> signAuth(String AccessToken) {
		HashMap m = new HashMap();
		try {
			SignAuthBean sab = new SignAuthBean();
			SignAuthCall sac = new SignAuthCall();
			sab.setToken(AccessToken);
			sab.setSClientType("MainSite");
			sac.setData(false, sab);
			Logger.comment("用户token登录认证");
			sac.callService();
			Logger.debug("Token认证 call:" + sac.getEntityString());
			Logger.debug("Token认证 response:" + sac.getReturnData());
			m.put("success", sac.getSuccess());
			if (sac.getSuccess()) {
				m.put("userId", sac.getUserId());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}
	/**
	 * Token认证
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, String> removeAuth(String AccessToken) {
		HashMap m = new HashMap();
		try {
			RemoveTokenBean lab = new RemoveTokenBean();
			RemoveTokenCall lac = new RemoveTokenCall();
			lab.setToken(AccessToken);
			lac.setData(false, lab);
			lac.callService();
			Logger.debug("移除Token认证 call:" + lac.getEntityString());
			Logger.debug("移除Token认证 response:" + lac.getReturnData());

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}
	/**
	 * *更新用户的IP区域认证状态为已认证
	 */
	@SuppressWarnings("rawtypes")
	public static IpAreaAuthManageRequestDtoCall ipAreaAuthManage(String country,String province,String city,int userid) {
		 IpAreaAuthManageRequestDtoBean ipareaauthmanagerequestdtoBean=new IpAreaAuthManageRequestDtoBean();
		 IpAreaAuthManageRequestDtoCall ipareaauthmanagerequestdtoCall=new IpAreaAuthManageRequestDtoCall();
		try {
			ipareaauthmanagerequestdtoBean.setCountry(country);
			ipareaauthmanagerequestdtoBean.setProvince(province);
			ipareaauthmanagerequestdtoBean.setCity(city);
			ipareaauthmanagerequestdtoBean.setUserId(userid);
			ipareaauthmanagerequestdtoCall.setData(ipareaauthmanagerequestdtoBean);
			ipareaauthmanagerequestdtoCall.callService();
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ipareaauthmanagerequestdtoCall;
	}
	
	/**
	 * 修改登入密码
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, String> modifyLoginPassword(String UserId, String pas) {
		HashMap m = new HashMap();
		try {
			PasswordRequestDtoBean lab = new PasswordRequestDtoBean();
			PasswordRequestDtoCall lac = new PasswordRequestDtoCall();
			lab.setUserId(UserId);
			lab.setNewPassword(pas);
			lab.setAType("ByUserId");
			lab.setPasActionType("ModifyLoginPassword");
			lac.setData(false, lab);
			lac.callService();
			Logger.debug("修改登入密码 call:" + lac.getEntityString());
			Logger.debug("修改登入密码 response:" + lac.getReturnData());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}
	
	/**
	 * 认证IP
	 * @param ip 登陆IP
	 * @param loginId 登录Id
	 * @param pwd 登陆密码
	 * @param sourceType 使用的终端（mainsite, main...）
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static void authIPArea(String ip, String loginId, String pwd, String sourceType) throws ClientProtocolException, IOException{
		IpAreaAuthStatusRequestDtoBean ipareaauthstatusrequestdtoBean=new IpAreaAuthStatusRequestDtoBean();
		IpAreaAuthStatusRequestDtoCall ipareaauthstatusrequestdtoCall=new IpAreaAuthStatusRequestDtoCall();
		ipareaauthstatusrequestdtoBean.setIp(ip);
		ipareaauthstatusrequestdtoBean.setLoginId(loginId);
		ipareaauthstatusrequestdtoBean.setPassword(pwd);
		ipareaauthstatusrequestdtoBean.setSuccess(true);
		ipareaauthstatusrequestdtoBean.setSource(sourceType);
		ipareaauthstatusrequestdtoCall.setData(ipareaauthstatusrequestdtoBean);
		ipareaauthstatusrequestdtoCall.callService();	
		Logger.verifyEquals("true", ipareaauthstatusrequestdtoCall.getString("Success"), "验证认证成功");
	}
	
	/**
	 * 设备认证
	 * @param clientId 设备clientId
	 * @param deviceId 设备Id
	 * @param loginId 登录Id
	 * @param pwd 登陆密码
	 * @param sourceType 登陆终端
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void authApp(String clientId, String deviceId, String loginId, String pwd, String sourceType) throws ClientProtocolException, IOException{
		DeviceAuthStatusRequestDtoBean deviceauthstatusrequestdtoBean=new DeviceAuthStatusRequestDtoBean();
		DeviceAuthStatusRequestDtoCall deviceauthstatusrequestdtoCall=new DeviceAuthStatusRequestDtoCall();
		deviceauthstatusrequestdtoBean.setClientId(clientId);
		deviceauthstatusrequestdtoBean.setDeviceId(deviceId);
		deviceauthstatusrequestdtoBean.setIp(TestDataManager.getRandomIp());
		deviceauthstatusrequestdtoBean.setLoginId(loginId);
		deviceauthstatusrequestdtoBean.setPassword(pwd);
		deviceauthstatusrequestdtoBean.setSource(sourceType);
		deviceauthstatusrequestdtoBean.setSuccess(true);
		deviceauthstatusrequestdtoCall.setData(deviceauthstatusrequestdtoBean);
		deviceauthstatusrequestdtoCall.callService();
		Logger.verifyEquals("true", deviceauthstatusrequestdtoCall.getString("Success"), "验证认证成功");
	}
	

	/**
	 * 修改支付密码 不生效 需要调用userservice 才能生效
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	// @SuppressWarnings("rawtypes")
	// public static Map<String, String> ModifyTradingPassword(String UserId,
	// String pas) {
	// HashMap m = new HashMap();
	// try {
	// PasswordRequestDtoBean lab = new PasswordRequestDtoBean();
	// PasswordRequestDtoCall lac = new PasswordRequestDtoCall();
	// lab.setUserId(UserId);
	// lab.setNewPassword(pas);
	// lab.setAType("ByUserId");
	// lab.setPasActionType("ModifyTradingPassword");
	// lac.setData(false,lab);
	// lac.callService();
	// Logger.debug("修改支付密码 call:" + lac.getEntityString());
	// Logger.debug("修改支付密码 response:" + lac.getReturnData());
	// } catch (ClientProtocolException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// return m;
	// }
	/**
     * 修改支付密码
     * @param userId
     * @param newTradingpwd
     */
    public static void updatePayPassWord(String userId,String newTradingpwd) {
    	Logger.comment("修改支付密码");
    	PasswordRequestDtoBean passbean=new PasswordRequestDtoBean();
    	PasswordRequestDtoCall passcall=new PasswordRequestDtoCall();
        try {
        	passbean.setAType("ByUserId");
        	passbean.setPasActionType("ModifyTradingPassword");
        	passbean.setUserId(userId);
        	passbean.setNewPassword(newTradingpwd);
        	passcall.setData(false, passbean);
        	passcall.callService();
        } catch (Exception e) {
            Logger.fail(e);
        }

    }
	/**
	 * @param loginId
	 * @param ip
	 * @param type
	 * @return 
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static IpAreaAuthStatusRequestDtoCall ipAreaAuthStatus(String loginId,String ip,String type) throws Exception{
		IpAreaAuthStatusRequestDtoBean ipareaauthstatusrequestdtoBean=new IpAreaAuthStatusRequestDtoBean();
		IpAreaAuthStatusRequestDtoCall ipareaauthstatusrequestdtoCall=new IpAreaAuthStatusRequestDtoCall();
		ipareaauthstatusrequestdtoBean.setIp(ip);
		ipareaauthstatusrequestdtoBean.setLoginId(loginId);
		ipareaauthstatusrequestdtoBean.setPassword("123456a");
		ipareaauthstatusrequestdtoBean.setSuccess(true);
		ipareaauthstatusrequestdtoBean.setSource(type);
		ipareaauthstatusrequestdtoCall.setData(ipareaauthstatusrequestdtoBean);
		ipareaauthstatusrequestdtoCall.callService();	
		return ipareaauthstatusrequestdtoCall;
	} 
	/**
	 * 给userid用户设置安全问题
	 * @param userid
	 * @throws Exception
	 */
	public static List<SecurityQuestionAnswer> setSecurityQuestion(Integer userid) throws Exception{
		Logger.comment("设置安全问题，userid:"+userid);
		List<SecurityQuestionAnswer> securityQuestionAnswerList=new ArrayList<>();
		SecurityQuestionAnswer securityQuestionAnswer1=new SecurityQuestionAnswer();
		securityQuestionAnswer1.setQuestionId(1);
		securityQuestionAnswer1.setQuestionAnswer("测试1");
		securityQuestionAnswerList.add(securityQuestionAnswer1);
		
		SecurityQuestionAnswer securityQuestionAnswer2=new SecurityQuestionAnswer();
		securityQuestionAnswer2.setQuestionId(2);
		securityQuestionAnswer2.setQuestionAnswer("测试2");
		securityQuestionAnswerList.add(securityQuestionAnswer2);
		
		SecurityQuestionAnswer securityQuestionAnswer3=new SecurityQuestionAnswer();
		securityQuestionAnswer3.setQuestionId(3);
		securityQuestionAnswer3.setQuestionAnswer("测试3");
		securityQuestionAnswerList.add(securityQuestionAnswer3);
		
		SetSecurityQuestionBean setsecurityquestionBean=new SetSecurityQuestionBean();
		SetSecurityQuestionCall setsecurityquestionCall=new SetSecurityQuestionCall();
		
		setsecurityquestionBean.setUserId(userid);
		setsecurityquestionBean.setSecurityQuestionAnswerList(securityQuestionAnswerList);
		setsecurityquestionCall.setData(setsecurityquestionBean);
		setsecurityquestionCall.callService();			
		return securityQuestionAnswerList;
	} 
	/**
	 * 设置是否开启双重验证
	 * @param userid
	 * @param enable
	 * @return
	 * @throws Exception
	 */
	public static SetDualSecurityRequestDtoCall setSecurity(Integer userid,Boolean enable) throws Exception{
		Logger.comment("设置双重认证，userid:"+userid+",enable:"+enable);
		SetDualSecurityRequestDtoBean setdualsecurityrequestdtoBean=new SetDualSecurityRequestDtoBean();
		SetDualSecurityRequestDtoCall setdualsecurityrequestdtoCall=new SetDualSecurityRequestDtoCall();
		setdualsecurityrequestdtoBean.setUserId(userid);
		setdualsecurityrequestdtoBean.setEnable(enable);
		setdualsecurityrequestdtoCall.setData(setdualsecurityrequestdtoBean);
		setdualsecurityrequestdtoCall.callService();	
		return setdualsecurityrequestdtoCall;
	}
	/**
	 * 查询双重验证
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	public static GetDualSecurityResultRequestDtoCall getSecurity(Integer userid) throws Exception{
		GetDualSecurityResultRequestDtoBean setdualsecurityrequestdtoBean=new GetDualSecurityResultRequestDtoBean();
		GetDualSecurityResultRequestDtoCall setdualsecurityrequestdtoCall=new GetDualSecurityResultRequestDtoCall();
		setdualsecurityrequestdtoBean.setUserId(userid);
		setdualsecurityrequestdtoCall.setData(setdualsecurityrequestdtoBean);
		setdualsecurityrequestdtoCall.callService();	
		return setdualsecurityrequestdtoCall;
	} 
	public static void main(String[] args) {
//		Logger.debug(AuthCallService.modifyLoginPassword("554416", "123456a"));
		ArrayList<String> list=TestDataManager.getLines("./login");
		for (String string : list) {
			AuthCallService.authLogin(string, "1234D4321","app",TestDataManager.getRandomIp());
		}
		
		// Logger.debug(AuthCallService.authLogin("丁丁", "123456a"));

	}
}
